import { useEffect, useState } from "react";
import { useModel } from "umi";
import { Button, Checkbox, message, Form, Select, Space } from "antd";
import { useReactive } from "ahooks";
import { v4 as uuidv4 } from "uuid";

import usePosition from "../../hooks/position/usePosition";
import useStaff from "../../hooks/staff/useStaff";
import useAddPosition from "../../hooks/institution/useAddPosition";

const AddDepartmentPosition = ({ department, reloadData }) => {
    const { loading, positions } = usePosition();
    const { loading: staffLoading, staffs } = useStaff({});
    const { addInstitutionPosition } = useAddPosition();

    const [form] = Form.useForm();

    const state = useReactive({
        bntloading: false,
        selectedStaff: [],
    });

    useEffect(() => {
        form.resetFields();
    }, [department]);

    const onStaffChange = (value, option) => {
        state.selectedStaff = option;
    };

    const onFinish = async (values) => {
        let index = department.children.findIndex((item) => item.staff?.osUuid === state.selectedStaff.osUuid);
        if (index >= 0) return message.warning("该员工已经在该部门下了，不能重复添加");
        state.bntloading = true;
        let data = {
            reUuid: uuidv4(),
            oiUuid: department.oiUuid,
            reType: "内部",
            osUuid: state.selectedStaff.osUuid,
            omUuid: state.selectedStaff.omUuid || null,
            opUuid: values.opUuid,
        };
        await addInstitutionPosition(data, () => {
            reloadData();
            form.resetFields();
        });
        state.bntloading = false;
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item label="职位" name="opUuid" rules={[{ required: true }]}>
                <Select allowClear placeholder="请选择" loading={loading} options={positions} fieldNames={{ label: "opName", value: "opUuid" }} />
            </Form.Item>

            <Form.Item label="人员" name="osUuid" rules={[{ required: true }]}>
                <Select allowClear placeholder="请选择" loading={staffLoading} options={staffs} fieldNames={{ label: "osName", value: "osUuid" }} onChange={onStaffChange} />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.bntloading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.bntloading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default AddDepartmentPosition;
